//
//  SystemInfoController.m
//  DataStatistics
//
//  Created by YTYanK on 16/4/24.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "SystemInfoController.h"
#import "EquipmenDetailsViewModel.h"
#import "DeviceDetailsModel.h"
#import "UITextField+LolitaText.h"
/// 定义 一个可以相互传值block 类型
typedef void (^textFieldVlueBlock)(_Nullable id vlue,   NSString * _Nullable  stampStr);

@interface SystemInfoController ()<UITextFieldLolitaDelegate,UITextFieldDelegate>
{
    int  count;
    IBOutlet NSLayoutConstraint *addEquipmentBtn_to;
    IBOutlet NSLayoutConstraint *tableView_H;
}
@property (strong, nonatomic) IBOutlet UITextField *nickNameText;
@property (weak, nonatomic) IBOutlet UINavigationItem *info_navItem;
@property (strong, nonatomic) NSArray *infoAry;
@property (copy, nonatomic) NSString *scanStr;
@property (weak, nonatomic) IBOutlet UINavigationBar *topnavigation;

@property (weak, nonatomic) IBOutlet UIView *topview;
@property (strong, nonatomic) NSString *nickVlue; //输入上传的昵称


@end


@implementation SystemInfoController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self upadateUI];
    // Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (SCREEN_HEIGHT == 480) {
        tableView_H.constant = 70;//210;
        addEquipmentBtn_to.constant = 20;
    }else  if(SCREEN_HEIGHT == 568){
        tableView_H.constant = 120;//140;
        addEquipmentBtn_to.constant = 30;
    }else if (SCREEN_HEIGHT == 667) {
        tableView_H.constant = 120;
        addEquipmentBtn_to.constant = 30;
    }else if (SCREEN_HEIGHT == 736) {
        tableView_H.constant =130; //150
        addEquipmentBtn_to.constant = 35;
    }

}


- (void)upadateUI {

//   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addYTYanK_textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:_nickNameText];
//    self.nickNameText.textFieldBlock = ^(id textField , NSString * str){
//        UITextField * field = (UITextField *)textField;
//        if (field.text.length > 8)
//            field.text = [field.text substringToIndex:8];
//        
//        _nickVlue = field.text;
//    };
//    self.nickNameText.delegate = self;
//    
//    [UITextField addYTYanKTextFielStyle1:_nickNameText withString:NSLocalizedString(@"SIvcLead_nickName",nil)];
//     self.nickNameText.enablesReturnKeyAutomatically  = NO;
    
    self.topview.backgroundColor   = RGB(26, 32, 40, 1.0);
    self.topnavigation.barTintColor = RGB(7, 13, 20, 1.0);
    self.view.backgroundColor        = RGB(33, 38, 44, 1.0);

    // 进入修改昵称页面
    if(self.marked != nil) {
        NSDictionary* parameters     = @{ @"deviceNo" : self.sys_deviceCode };
        [EquipmenDetailsViewModel requestWithUrlForDeviceDetails:self andParam:parameters success:^(DeviceDetailsModel *model) {
            if ( model != nil) {
                self.detailsAry = [NSMutableArray arrayWithObjects:model,nil];
                [self.infoTableView reloadData];
            }
            
        } failure:^(NSString *error) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
        }];
         self.nickVlue =  self.nickNameText.text = [NSUD objectForKey:MDC_NICK_NMAE];
         self.nickNameText.enablesReturnKeyAutomatically = YES;
    }
   

      self.nickNameText.returnKeyType = UIReturnKeyDone;
    self.navigationController.navigationBar.barTintColor =RGB(26, 32, 40, 1);
    //这个判断是否需要？
       if ( [ROLEDODE isEqualToString:@"001"] )  {
           self.addSystemBtn.hidden = YES;
       }else {
           self.addSystemBtn.hidden = NO;
       }

        if (self.marked == nil) {
             [self.addSystemBtn setTitle:NSLocalizedString(@"Sys_addDevice", @"添加设备") forState:UIControlStateNormal];
        }else {
             [self.addSystemBtn setTitle:NSLocalizedString(@"Sys_modifyDevice", @"保存") forState:UIControlStateNormal];
        }
   
    
    self.infoTableView.userInteractionEnabled = NO;
    self.infoTableView.separatorColor = [UIColor grayColor];
    self.infoTableView.backgroundColor = [UIColor clearColor];
    [self initNavigationItem];
}

- (NSString *)updateViewDataAtIndexPath: (NSIndexPath *)indexPath {
    NSArray *ary = self.detailsAry;
    __weak NSString *constStr = @"---";
    __weak NSString *ontainerStr = @"";
    
    switch (indexPath.row) {
//        case 0:
//            ontainerStr = @"";//[NSString stringWithFormat:@"%@",[ary[0] device_name]];
//            break;
        case 0:
            ontainerStr = [NSString stringWithFormat:@"%@",[ary[0] device_name]];
            break;
            case 1:
            ontainerStr = [NSString stringWithFormat:@"%@",[ary[0] device_id]];
            break;
            
        default:
            break;
    }
    
    if ([ontainerStr isEqualToString:@"(null)"] || ontainerStr == nil)
        ontainerStr = constStr;

    return ontainerStr;
}


- (void)initNavigationItem {
    self.navigationController.navigationBar.backgroundColor = RGB(40, 255, 255, 1);
    if (self.marked != nil) {
        self.info_navItem.title = NSLocalizedString(@"Sys_modify",@"修改");
    }else {
        self.info_navItem.title = NSLocalizedString(@"Sys_addDevice",@"详情");
    }
    
    self.info_navItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"返回" highImageName:@"返回" title:nil target:self action:@selector(ReturnBtn)];
}


- (IBAction)addSystem:(UIButton *)sender {
    //去两端空格和回车
/*    self.nickVlue = [self.nickVlue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (self.nickVlue.length == 0 || self.nickNameText.text.length == 0) {
        //请输入有效名称
        [MBProgressHUD showError:@"昵称不能为空"];
        return;
    }*/
    
    NSDictionary *parameters;
    if(self.marked == nil) {
        parameters = [NSDictionary dictionaryWithObjectsAndKeys:[self.scanStr substringFromIndex:(self.scanStr.length - 22)],@"deviceQRCode",@"---",@"nickname", nil];
    }else {
      parameters = @{@"deviceNo":self.sys_deviceCode,@"nickname":self.nickVlue,@"querDetailList":@"nickname.asp"};
    }
    
       [EquipmenDetailsViewModel requestWithUrlForDeviceBinding:self andParam:parameters success:^(id model) {
           if (self.marked == nil) {
               if (self.delegate != nil && [self.delegate respondsToSelector:@selector(dismissViewControllerWithDeviceVlue:)]) {
                   [self.delegate dismissViewControllerWithDeviceVlue:model];
               }
           }else {
               [NSUD  setObject:self.nickVlue forKey:MDC_NICK_NMAE];
               [NSNC postNotificationName:MDC_NOTIFICATION_NICK object:nil];
               [MBProgressHUD showSuccess:model];
           }
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
       } failure:^(NSString *error) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
       }];
}


// 监控NickName中文输入方法(限制长度)
- (void)addYTYanK_textFiledEditChanged:(NSNotification *)obj {
    UITextField* textfield = (UITextField*)obj.object;
    [_nickNameText YTYanKTextFiledEditChangedObj:textfield];
}

- (void)ReturnBtn {
    [self dismissViewControllerAnimated:YES completion:nil];
    if ([[NSUD objectForKey:MDC_SET_MASKVIEW] isEqualToString:@"加遮"]) {
        [self.delegate onTopBackDown:self];
        return;
    }
}

#pragma mark - UITableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoAry.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cellHeight =[self tableView:tableView cellForRowAtIndexPath:indexPath];
    float heightFloat = CGRectGetHeight(cellHeight.frame);
    
    if (SCREEN_HEIGHT == 480) {
        heightFloat = 35;
    }else if (SCREEN_HEIGHT == 667){
        heightFloat = 50;
    }else if (SCREEN_HEIGHT == 736) {
        heightFloat = 50;
    }
    return heightFloat;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *idenfitier = @"coustomerList";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:idenfitier];
   
    
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont systemFontOfSize:15.f];
    cell.textLabel.textColor = [UIColor grayColor];
    cell.textLabel.text = self.infoAry[indexPath.row];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14.f];
    cell.detailTextLabel.text =[self updateViewDataAtIndexPath:indexPath];
    cell.detailTextLabel.textColor = [UIColor grayColor];
    
    return cell;
}

#pragma mark - TextFile
//键盘return调用方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    if([self.view viewWithTag:textField.tag+1])
        [[self.view viewWithTag:textField.tag+1] becomeFirstResponder];
    
    [self addSystem:_addSystemBtn];
    
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{
    [self.view endEditing:YES];
}




#pragma mark - get/set
- (NSString *)scanStr {
    if (!_scanStr) {
        _scanStr = SCANINFO;
    }
    return _scanStr;
}


- (NSArray *)infoAry {
    if (!_infoAry) {
        _infoAry = [[NSArray alloc] initWithObjects:NSLocalizedString(@"SysLead_1",nil),NSLocalizedString(@"  设备编号", nil), nil];
    }
    return _infoAry;
}

@end
